package net.wwang.blog.service;

import net.wwang.blog.commons.global.Constants;
import net.wwang.blog.pojo.User;
import net.wwang.blog.util.CookieUtil;
import net.wwang.blog.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author WangWei
 * @date 2020/8/14
 */
@Service("permission")
public class PermissionService {
    @Autowired
    private UserService userService;
    /**
     * 判断是否是管理员
     * @return
     */
    public boolean isRoleAdmin(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        String tokenKey = CookieUtil.getCookie(request, Constants.User.SYSTEM_COOKIE_TOKEN);
        if(Utils.isEmpty(tokenKey)){
            return false;
        }
        User user = userService.checkUserState(request, response);
        if (user == null) {
            return false;
        }
        String roles = user.getRoles();
        String[] role = roles.split(",");
        for (String s : role) {
            if(s.equals(Constants.User.ROLE_ADMIN)){
                return  true;
            }
        }
        return false;
    }
}
